package com.juguo.charginganimation.View.gallery;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.chad.library.adapter.base.module.BaseLoadMoreModule;
import com.juguo.charginganimation.Adapter.GalleryAdapter;
import com.juguo.charginganimation.Base.BaseFragment;
import com.juguo.charginganimation.Bean.PhotoBean;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.utils.UITools;
import com.juguo.charginganimation.repository.PixabayService;

import java.util.List;

import io.reactivex.disposables.CompositeDisposable;

public class MenuRockGallery extends BaseFragment {

    private static final String TAG = "McoolGallery";
    private CompositeDisposable mDisposable = new CompositeDisposable();
    private PixabayService service = RetrofitManager.getInstance().getRetrofit().create(PixabayService.class);
    MutableLiveData<List<PhotoBean.Photos>> photos = new MutableLiveData<>();
    /**
     * 数据源
     */
    private GalleryViewModel mViewModel;

    private RecyclerView recyclerViewGallery;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GalleryAdapter galleryAdapter;

    //加载更多事件处理类
    private BaseLoadMoreModule loadMore;

    //暂存当前页数
    private int currentPage = 1;

    //暂存总页数
    private int totalPage = 1;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View root = inflater.inflate(R.layout.fragment_gallery_chouti, container, false);
        initView(root);
        return root;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_gallery_chouti;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause()");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated");

        //viewModel初始化
        mViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication())).get(GalleryViewModel.class);

        //recyclerView Adapter初始化 使用 BRVAH 框架
        galleryAdapter = new GalleryAdapter();
        galleryAdapter.setDiffCallback(new McoolGallery.MyDiffCallback());

        //开启滑动动画
        galleryAdapter.setAnimationEnable(true);

        //动画只执行一次
        galleryAdapter.setAnimationFirstOnly(false);

        //设置空视图
        galleryAdapter.setEmptyView(initEmptyView("正在初始化资源..."));

        //加载更多对象，来自于BRVAH
        loadMore = galleryAdapter.getLoadMoreModule();
        loadMore.isAutoLoadMore();

        //交错布局，2列，纵向
        recyclerViewGallery.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        recyclerViewGallery.setAdapter(galleryAdapter);

        //定制ScrollListener
//        recyclerViewGallery.addOnScrollListener(new MyRecyclerViewScrollListener());

        //数据源：hitsBean观察者，如果hitsBean发生变化则更新recycleView
        mViewModel.photos.observe(getViewLifecycleOwner(), new Observer<List<PhotoBean.Photos>>() {
            @Override
            public void onChanged(List<PhotoBean.Photos> photos) {
                galleryAdapter.setDiffNewData(photos);
                swipeRefreshLayout.setRefreshing(false);
                //数据发生变化时，重新获取总页数
                totalPage = mViewModel.getTotalPage();
            }
        });

        //如果_hitsBean为空，则获取数据
        if (mViewModel.photos.getValue() == null) {
            mViewModel.menurock();
            //重新获取页数
            currentPage = mViewModel.getCurrentPage() + 1;
        }

        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mViewModel.menurock();
                //重新获取页数
                currentPage = mViewModel.getCurrentPage() + 1;
                loadMore.loadMoreComplete();
            }
        });

        //Item点击事件,进入详细页面
        galleryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                //将图片信息传输到detail页面
                Bundle bundle = new Bundle();
                bundle.putParcelable("CHECKED_PHOTO_ID", (Parcelable) adapter.getItem(position));
                Intent intent = new Intent(getContext(), GalleryDetail.class);
                intent.putExtras(bundle); //传bundle对象
                //过度效果
                ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), view, "detail_img");
                ActivityCompat.startActivity(getActivity(), intent, compat.toBundle());
            }
        });

        /**
         * 当recycleView滑动到底部时执行此监听
         */
        loadMore.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreGallery();
            }
        });

    }

    /**
     * 控件初始化
     *
     * @param root
     */
    public void initView(View root) {
        swipeRefreshLayout = root.findViewById(R.id.swipeGallery);
        recyclerViewGallery = root.findViewById(R.id.recyclerview_gallery);
        //状态栏文字透明
        UITools.makeStatusBarTransparent(getActivity());

    }

    @Override
    protected void initData(Context mContext) {

    }

    /**
     * 初始化空列表视图
     *
     * @param tip 空视图提示信息
     * @return 空列表视图 view
     */
    private View initEmptyView(String tip) {
        View emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
        TextView emptyTextView = emptyView.findViewById(R.id.emptytextView);
        emptyTextView.setText(tip);
        return emptyView;
    }

    /**
     * 加载更多数据
     */
    private void loadMoreGallery() {
        Log.d(TAG, "加载更多 -> currentPage：" + currentPage + "\t totalPage：" + totalPage + "\tkey：");
        if (currentPage > totalPage) {
            loadMore.loadMoreEnd();
            return;
        } else {
            mViewModel.menurock();
        }
    }

    /**
     * 指定DiffUtil类，判断item是否相同
     */
    static class MyDiffCallback extends DiffUtil.ItemCallback<PhotoBean.Photos> {
        @Override
        public boolean areItemsTheSame(@NonNull PhotoBean.Photos oldItem, @NonNull PhotoBean.Photos newItem) {
            return oldItem.getId() == newItem.getId();
        }

        @SuppressLint("DiffUtilEquals")
        @Override
        public boolean areContentsTheSame(@NonNull PhotoBean.Photos oldItem, @NonNull PhotoBean.Photos newItem) {
            return oldItem.equals(newItem);
        }

    }
}
